package com.nq.utils.task.stock;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.nq.common.ServerResponse;
import com.nq.common.constant.WebsocketConst;
import com.nq.common.entity.StStockTickerDetails;
import com.nq.common.entity.info.StockTickerListInfo;
import com.nq.message.websocket.WebSocket;
import com.nq.message.websocket.WebSocketUtils;
import com.nq.pojo.vo.StockOptionVo;
import com.nq.service.IStockOptionService;
import com.nq.utils.redis.RedisShardedPoolUtils;
import com.nq.utils.task.tsanghi.StocksComponent;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Component
public class StockOptionTask {

    // 收藏列表实时数据
    public static final String ST_STOCK_OPTION_REAL_TIME_DATA_LIST_KEY = "real_time_data_option_key";
    @Resource
    private IStockOptionService stockOptionService;

    private static StocksComponent stocksComponent;
    @Autowired
    public void setStocksComponent(StocksComponent stocksComponent) {
        StockOptionTask.stocksComponent = stocksComponent;
    }

    @Autowired
    private WebSocket webSocket;

    private static final Logger log = LoggerFactory.getLogger(StockOptionTask.class);

    /**
     * 定时推送股票收藏实时行情
     */
//    @Scheduled(cron = "0/5 * * * * ?")
    public void pushOptionListDataToClient() {

        log.info("############定时推送股票收藏实时行情开始######################");
        List<String> keysByPrefix = RedisShardedPoolUtils.getKeys(ST_STOCK_OPTION_REAL_TIME_DATA_LIST_KEY);
        for (String key : keysByPrefix) {
            String[] splitKey = key.split(":");
            List<String> stringList = Arrays.asList(splitKey);
            if (stringList.size() == 2) {
                String random = stringList.get(1);

                // 从适当的来源获取最新的 market 和 stockCodes
                String listMessage = RedisShardedPoolUtils.get(key);
                try {
                    if (StringUtils.isNotBlank(listMessage)) {
                        // 处理查询股票列表的数据格式
                        String[] optionParam = listMessage.split(";");
                        List<String> optionParamList = Arrays.asList(optionParam);
                        if (optionParamList.size() == 6) {
                            String userId = optionParamList.get(1);
                            String changePercent = optionParamList.get(2);
                            int pageNo = Integer.parseInt(optionParamList.get(3));
                            int pageSize = Integer.parseInt(optionParamList.get(4));

                            // 获取收藏列表
                            ServerResponse<PageInfo> pageList = stockOptionService.findOptionListByParam(userId, changePercent, pageNo, pageSize);

                            // 存储详情
                            ArrayList<StockTickerListInfo> infos = new ArrayList<>();
                            if(pageList.isSuccess()) {
                                List<StockOptionVo> optionVos = pageList.getData().getList();
                                for (StockOptionVo optionVo : optionVos) {
                                    String code = optionVo.getStockCode();
                                    String market = optionVo.getMarket();
                                    if (StringUtils.isNotBlank(code) && StringUtils.isNotBlank(market)) {
                                        StStockTickerDetails details = stocksComponent.queryDetailsByMarketAndCode(market, code);

                                        // stocksComponent.thirdInterfaceStatistic(StocksComponent.MINI_PRICES, "pushOptionListDataToClient");

                                        if (null != details) {
                                            StockTickerListInfo data = details.getData();
                                            if (null != data) {
                                                infos.add(data);
                                            }
                                        }
                                    }
                                }
                            }
                            if (!infos.isEmpty()) {
                                Session session = WebSocketUtils.getSession();
                                if(null != session && session.isOpen()) {
                                    JSONObject obj = new JSONObject();
                                    obj.put(WebsocketConst.NEWS_PUBLISH, WebsocketConst.STOCK_OPTION_LIST);//业务类型
                                    obj.put(WebsocketConst.MSG_TXT, infos);//消息内容
                                    webSocket.sendOneMessage(userId, obj.toJSONString());
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("股票收藏列表实时刷新定时任务异常。。。{}", e.getMessage());
                }

            }
        }


    }

}